package com.ruoyi.cderp.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cderp.mapper.CategoryMapper;
import com.ruoyi.cderp.domain.Category;
import com.ruoyi.cderp.service.ICategoryService;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 分类Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-06
 */
@Service
public class CategoryServiceImpl implements ICategoryService
{
    @Autowired
    private CategoryMapper categoryMapper;

    LoginUser loginUser = null;

    /**
     * 查询分类
     *
     * @param id 分类主键
     * @return 分类
     */
    @Override
    public Category selectCategoryById(String id)
    {
        return categoryMapper.selectCategoryById(id);
    }

    /**
     * 查询分类列表
     *
     * @param category 分类
     * @return 分类
     */
    @Override
    public List<Category> selectCategoryList(Category category)
    {
        return categoryMapper.selectCategoryList(category);
    }

    /**
     * 新增分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int insertCategory(Category category)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String formattedDate = sdf.format(new Date());
        Random random = new Random();
        int randomNumber = 10000000 + random.nextInt(90000000); // 生成8位数随机数
        category.setId("18" + formattedDate+randomNumber);
        category.setCreateTime(DateUtils.getNowDate());
        // 获取当前登录用户对象
        loginUser = SecurityUtils.getLoginUser();
        category.setCreateBy(loginUser.getUser().getUserName());
        category.setCreateTime(DateUtils.getNowDate());
        return categoryMapper.insertCategory(category);
    }

    /**
     * 修改分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int updateCategory(Category category)
    {
        // 获取当前登录用户对象
        loginUser = SecurityUtils.getLoginUser();
        category.setUpdateBy(loginUser.getUser().getUserName());
        category.setUpdateTime(DateUtils.getNowDate());
        return categoryMapper.updateCategory(category);
    }

    /**
     * 批量删除分类
     *
     * @param ids 需要删除的分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByIds(String[] ids)
    {
        return categoryMapper.deleteCategoryByIds(ids);
    }

    /**
     * 删除分类信息
     *
     * @param id 分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryById(String id)
    {
        return categoryMapper.deleteCategoryById(id);
    }
}
